﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace paraInterface
{
    internal class Ini
    {
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
        private string _filename;
        public Ini() { }
        public Ini(string filename)
        {
            this.Filename = filename;
        }
        public string Filename
        {
            get { return _filename; }
            set
            {
                FileInfo file = new FileInfo(value);
                if ((!file.Exists))
                {
                    StreamWriter sw = new StreamWriter(value);
                    try
                    {
                        sw.Write("[CreatIni]");
                        sw.Close();
                    }
                    catch
                    {
                        throw (new ApplicationException("Ini文件不存在"));
                    }
                }
                _filename = file.FullName;
            }
        }

        public void Write(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, _filename);
        }

        public string ReadValue(string section, string key)
        {
            StringBuilder temp = new StringBuilder(10240);
            GetPrivateProfileString(section, key, "", temp, 1024, _filename);
            return temp.ToString();
        }
    }
}
